﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Hangfire.HttpJob.CSRedis
{
    /// <summary>
    /// agent job 调用注册
    /// </summary>
    internal class AgentJobInvoker
    {
        readonly IHttpClientFactory _httpClientFactory;
        readonly ILogger<AgentJobInvoker> _logger;

        /// <summary>
        /// ctor
        /// </summary>
        public AgentJobInvoker(
            IHttpClientFactory httpClientFactory,
            ILogger<AgentJobInvoker> logger)
        {
            _httpClientFactory = httpClientFactory;
            _logger = logger;
        }

        /// <summary>
        /// 执行作业
        /// </summary>
        /// <param name="context">作业上下文</param>
        public async Task ExecuteAsync(AgentJobContext context)
        {
            var client = _httpClientFactory.CreateClient();
            client.DefaultRequestHeaders.Clear();
            client.Timeout = TimeSpan.FromSeconds(20);
            var reqMessage = new HttpRequestMessage(HttpMethod.Post, context.AgentUrl);
            var content = JsonConvert.SerializeObject(context);
            reqMessage.Content = new StringContent(content, Encoding.UTF8, "application/json");
            client.SendAsync(reqMessage);
            await Task.CompletedTask;
        }
    }
}
